import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
import {clearUserLocalStorage} from "../../../../utils/util";
const { authorization } = require('../../../../utils/location')
const app = getApp();


Page({

    /**
     * 页面的初始数据
     */
    data: {
        orders: [],
        markers: [],
        selected_ids: [],
        main_order_ids: [],
        select_all_status: false,
        show_upload: true, //显示上传
        deletable: true, //允许删除
        max_upload_size: 1048576 * 2,


        count: 0,
        area: '', //获取区域
        scale: 12.1,
        activeNames: ['1'],// 打开信息 按钮
        latitude: 0,   //获取当前位置
        longitude: 0,
        checked: true,
        image: '/templates/deliver/img/business.png',

        current_order_id: '',
        current_order_no: '',
        current_order_remark: '',
        current_delivery_photo: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        let now = (new Date().getTime()) / 1000;
        let expiration_time = wx.getStorageSync('expiration_time')
        let group = wx.getStorageSync('role')

        let current_delivery_man_id = wx.getStorageSync('current_delivery_man_id')
        if (!current_delivery_man_id || current_delivery_man_id == 0) {
            current_delivery_man_id = 0
        }

        if (group !== 'delivery') {
            clearUserLocalStorage()
            expiration_time = 0
        }

        /*if (now > expiration_time) {
            wx.reLaunch({
                url: '/pages/login/login',
            })
        }*/

        let access_token = wx.getStorageSync('access_token')
        let delivery_man = wx.getStorageSync('delivery_man')
        let delivery_district = wx.getStorageSync('delivery_district')
        let delivery_district_list = wx.getStorageSync('delivery_district_list')
        let delivery_list = wx.getStorageSync('delivery_list')
        this.setData({
            'access_token': access_token,
            'delivery_man': delivery_man,
            'delivery_district': delivery_district,
            'delivery_district_list': delivery_district_list,
            'delivery_list': delivery_list,
            'current_delivery_district_id': 0,
            'level': delivery_man.level,
            'current_delivery_man_id': current_delivery_man_id
        })
        this.get_in_return()
    },

    onCheck(e) {
        let selected_ids = e.detail
        let main_order_ids = this.data.main_order_ids
        console.log('selected_ids:', selected_ids)
        let select_all_status = false
        if (selected_ids.length ===   main_order_ids.length) {
            select_all_status = true
        }
        this.setData({
            selected_ids,
            select_all_status
        })
    },

    onTapMarker(e) {
        const markerId = parseInt(e.detail.markerId)
        const markers = this.data.markers;

        console.log(markerId)
        const marker = markers.find(m => m.id === markerId); // 根据地图标记的 id 找到对应的 marker
        console.log(marker)
        if (marker) {
            const query = wx.createSelectorQuery();
            query.select(marker.select_id).boundingClientRect(); // 根据订单 id 找到对应的卡片
            query.exec(function(res) {
                console.log('res', res)
                const cardRect = res[0];
                if (cardRect) {
                    wx.pageScrollTo({
                        scrollTop: cardRect.top,
                    });
                }
            });
        }
    },
    parseJsonOrEmptyArray(jsonString) {
        try {
            const parsed = JSON.parse(jsonString);
            if (Array.isArray(parsed)) {
                // 检查数组元素的结构，并进行转换
                return parsed.map(item => {
                    if (typeof item === 'object' && 'url' in item) {
                        return item; // 已经是 { url: 'https://xxxxx' } 格式
                    } else if (typeof item === 'object' && item.url) {
                        return item.url; // 处理 { url: { url: 'https://xxxxx' } } 格式
                    } else {
                        return {}; // 无效的对象格式，返回空对象
                    }
                });
            } else {
                return [];
            }
        } catch (e) {
            return [];
        }
    },
    ballPopup(e) {
        let that = this
        let index = parseInt(e.currentTarget.dataset.index)

        let current_order_id = e.currentTarget.dataset.order_id //获取传递的id参数
        let current_order = this.data.orders[index];
        current_order.delivery_photo = that.parseJsonOrEmptyArray(current_order.delivery_photo)
        this.setData({
            show_popup: true,
            current_order_id,
            current_order
        }) //打开弹窗
    },
    onPopupClose() {
        this.setData({
            show_popup: false,
        })
    },

    tap_avatar(e) {
        console.log(e)
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
        })
        let latitude = e.currentTarget.dataset.latitude //获取传递的id参数
        let longitude = e.currentTarget.dataset.longitude //获取传递的id参数
        this.setData({
            'scale': 17,
        })
        this.map = wx.createMapContext('locationM', this)
        this.map.moveToLocation({
            longitude: Number(longitude),
            latitude: Number(latitude),
            success: function () {

            }
        })
    },

    select_all(event) {
        let main_order_ids = this.data.main_order_ids
        let selected_ids = []
        for (let i = 0; i < main_order_ids.length; i++) {
            selected_ids.push(String(main_order_ids[i]))
        }
        this.setData({
            selected_ids: selected_ids,
            select_all_status: event.detail,
        })
        if (this.data.select_all_status === false) {
            this.setData({
                selected_ids: [],
            })
        }
        //console.log(this.data.result)
    },

    on_delivery_district_dropdown_change(e) {
        const current_delivery_district_id = e.detail;
        this.setData({
            current_delivery_district_id: current_delivery_district_id,
        });
        wx.setStorageSync('current_delivery_district_id', current_delivery_district_id);
        this.get_waiting_delivery();
    },
    on_delivery_dropdown_change(e) {
        const current_delivery_man_id = e.detail;
        this.setData({
            current_delivery_man_id: current_delivery_man_id,
        });
        wx.setStorageSync('current_delivery_man_id', current_delivery_man_id);
        //this.get_waiting_delivery();
    },

    async get_current_location() {
        let res = await authorization()
        console.log("authorization res", res)
        this.setData({
            'longitude': res.longitude,
            'latitude': res.latitude,
        })
        /*
        this.map.moveToLocation({
            longitude: Number(this.data.longitude),
            latitude: Number(this.data.latitude),
            success: function () {
                console.log("成功将地图中心移到定位点")
            }
        })
        */
    },



    /* 上传文件查看图片大小 */
    imgSize(event) {
        let imgMax = this.data.max_upload_size
        const {
            file
        } = event.detail; //获取上传文件数组
        for (let i = 0; i < file.length; i++) {
            if (file[i].size > imgMax) {
                Toast('大小超过2MB~')
            }
        }
    },

    afterReadLogo(event) {
        this.afterRead(event, 1)
    },
    afterReadPhoto(event) {
        this.afterRead(event, 2)
    },

    /* 上传文件后事件，处理照片放入OSS回显 */
    afterRead(event, image_type) {
        let that = this
        const {file} = event.detail;
        for (let i = 0; i < file.length; i++) {
            wx.uploadFile({
                url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
                filePath: file[i]['url'], //传递文件
                header: {
                    'Content-Type': 'application/json',
                    "x-api-key": this.data.access_token,
                },
                name: 'file', //获取照片信息的名称
                formData: {
                    drive: 'qiniu',
                    thumb: JSON.stringify([{
                        width: 100,
                        height: 100
                    }])
                },

                success(res) {
                    //{"code":200,
                    // "message":"OK",
                    // "data":
                    // {"name":"image_1718268075_gM3Y3oJL",
                    // "width":0,"height":0,
                    // "size":6950,
                    // "extension":"png",
                    // "url":"https://fuddoss.fuduoduoshop.com/images/2024/06/13/image_1718268075_gM3Y3oJL.png",
                    // "merge":false,"guid":"","type":"image/png","id":75,"formatter_size":"6,79 KiB","upload_type":"images"},"timestamp":1718268076}

                    let response = JSON.parse(res.data) //传过来的是json 需要转换成对象
                    let code = response.code
                    if (code === 200) {
                        let current_delivery_photo = that.data.current_delivery_photo
                        current_delivery_photo.push({
                            url:response.data.url,
                            name: response.data.name,
                            isImage: true,
                        })
                        that.setData({
                            current_delivery_photo
                        })
                    }
                }
            })
        }
    },
    /**
     * 删除上传的照片
     */

    imgDeleteLogo(event) {
        this.imgDelete(event, 1)
    },
    imgDeletePhoto(event) {
        this.imgDelete(event, 2)
    },
    imgDelete(event) {
        let that = this;
        let urlPath = event.detail.file.url
        wx.request({
            url: app.globalData.API + '/delivery/index/delete-qiniu-image',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": that.data.access_token,
            },
            data: {
                path: urlPath
            },
            method: "POST",
            success: res => {
                if (res.data.code === 200) {
                    const success = res.data.data;
                    if (success) {
                        let current_delivery_photo = that.data.current_delivery_photo
                        current_delivery_photo = current_delivery_photo.filter(item => item.url !== urlPath);
                        console.log(current_delivery_photo)
                        that.setData({
                            current_delivery_photo
                        })
                    }
                }
            }
        });
    },
    onRemarkInput(e) {
        let that = this
        let value = e.detail;
        let current_order = that.data.current_order
        current_order.delivery_remark = value
        this.setData({
            current_order
        });
    },
    submit_wms_order_remark() {
        let that = this
        let current_order = that.data.current_order
        console.log(current_order.delivery_remark)
        wx.request({
            url: app.globalData.API + '/delivery/index/remark-delivery-order',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                current_order,
            },
            success(res) {
                if (res.data.code === 200) {
                    Toast('提交成功~')
                    that.onPopupClose()
                } else {
                    Toast('提交失败~')
                }
            }
        })
    },



    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
       


    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
       
       

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    onDisplay({
        detail
    }) {
        console.log({
            detail
        })
        var markers = this.data.markers;
        wx.showModal({
            title: '提示',
            content: '是否切换开关？',
            success: (res) => {
                console.log(res.confirm)
                if (!detail) {
                    for (var i = 0; i < markers.length; i++) {
                        this.setData({
                            ["markers[" + i + "].callout.display"]: 'BYCLICK',
                            checked: detail
                        });
                    }
                    this.setData({
                        checked: detail
                    });
                } else {
                    for (var i = 0; i < markers.length; i++) {
                        this.setData({
                            ["markers[" + i + "].callout.display"]: 'ALWAYS',

                        });
                    }
                    this.setData({
                        checked: detail
                    });
                }

            },
        });
    },

    onChangeShowCallout(event) {

        const {
            value
        } = event.detail;
        console.log(value)
        this.data.markers.forEach((item, index) => {

            if (value) {
                this.setData({

                    ["markers[" + index + "].callout.display"]: 'ALWAYS'

                });
            } else {
                this.setData({

                    ["markers[" + index + "].callout.display"]: 'BYCLICK'

                });
            }

        })


    },

    queryOrder(e) {
        let order_no = e.currentTarget.dataset.order_no
        console.log(order_no)
        this.getViewOrderInfo(order_no)
    },

    getViewOrderInfo(order_no) {
        wx.request({
            url: app.globalData.API + '/delivery/index/query-order-info',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                order_no
            },
            success(res) {
                if (res.data.code === 200) {
                    const success = res.data.data;
                    if (success) {
                        let orderInfo = JSON.stringify(res.data.data)
                        console.log( 'orderInfo:', orderInfo)
                        wx.navigateTo({
                            url: '/templates/deliver/pages/orderInfo/orderInfo',
                            success(res) {
                                res.eventChannel.emit('orderInfo', orderInfo)
                            }
                        })
                    }
                }
            }
        })
    },

    async deliver_selected() {
        const that = this
        let selected_ids = that.data.selected_ids
        that.finish_return(selected_ids)
    },

    async deliver(e) {
        const that = this
        let contact = e.currentTarget.dataset.contact
        let order_id = e.currentTarget.dataset.order_id //获取传递的id参数
        let order_ids = []

        Dialog.confirm({
            title: '确认送达',
            message: '确定' + contact + '的订单已经送达',
        }).then(() => {
                order_ids.push(order_id)
                that.finish_return(order_ids)
            })
            .catch(() => {
                // on cancel
                Notify({
                    type: 'warning',
                    message: '取消送达'
                });
            });
    },


    async finish_return(order_ids) {
        const that = this

        /*for (let i =0;i<that.data.orders.length;i++) {
            order_ids.push(that.data.orders[i].order_id)
        }*/
        wx.request({
            url: app.globalData.API + '/delivery/index/finish-return',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                order_ids
            },
            success(res) {
                if (res.data.code === 200) {
                    const success = res.data.data;
                    if (success) {
                        wx.showToast({
                            title: '成功',
                            icon: 'success',
                            duration: 2000,
                        });

                        that.get_in_return()
                    }
                }
            }
        })
    },

    call_mobile(e) {
        let mobile = e.currentTarget.dataset.mobile
        console.log(mobile)
        wx.makePhoneCall({
            phoneNumber: mobile,
            success: function () {
                console.log("拨打电话成功！")
            },
            fail: function () {
                console.log("拨打电话失败！")
            }
        })
    },

    async get_in_return() {
        const that = this
        let current_delivery_man_id = that.data.current_delivery_man_id
        let current_delivery_district_id = that.data.current_delivery_district_id
        let delivery_status = 1

        await that.get_current_location()
        wx.request({
            url: app.globalData.API + '/delivery/index/get-in-return-orders',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                current_delivery_district_id,
                current_delivery_man_id,
                delivery_status
            },
            success(res) {
                if (res.data.code == 200) {
                    let orders = res.data.data.orders
                    let max_distance = res.data.data.max_distance
                    let markers = []
                    for (let i = 0; i < orders.length; i++) {

                        const longitude = orders[i].longitude; // 经度
                        const latitude = orders[i].latitude; // 纬度
                        orders[i].latitude = latitude
                        orders[i].longitude = longitude

                        orders[i].delivery_merge_id = parseInt(orders[i].delivery_merge_id)
                        orders[i].distance = that.getDistance(latitude, longitude, that.data.latitude, that.data.longitude)
                    }
                    orders.sort((a, b) => a.distance - b.distance);

                    let main_order_ids = [];
                    for (let i = 0; i < orders.length; i++) {
                        if (orders[i].delivery_merge_id === 0) {
                            main_order_ids.push(orders[i].order_id)
                            markers.push({
                                iconPath: "../../img/icon-hc.png",
                                id: 900000000 + parseInt(orders[i].order_id),
                                order_id: orders[i].order_id,
                                select_id: `#card-${orders[i].order_id}` ,
                                latitude: orders[i].latitude,
                                longitude: orders[i].longitude,
                                width: 23,
                                height: 23,

                                nearbyCount: 0,
                                nearMarkers: [],
                                nearMarkersInfo:[],

                                callout: {
                                    content: orders[i].contact + '' + (i+1),
                                    store_name: orders[i].contact ,
                                    fontSize: 14,
                                    padding: true,
                                    color: '#444',
                                    display: 'ALWAYS',
                                    textAlign: 'center',
                                    borderRadius: 5,
                                    bgColor: '#ffffff'
                                },
                            })
                        }
                    }

                    // 计算每两个定位点之间的距离
                    for (let i = 0; i < markers.length; i++) {
                        for (let j = i + 1; j < markers.length; j++) {
                            let distance = that.calculateDistance(markers[i].latitude, markers[i].longitude, markers[j].latitude, markers[j].longitude);
                            if (distance <= max_distance) {
                                markers[i].nearbyCount += 1;
                                markers[j].nearbyCount += 1;

                                markers[i].nearMarkers.push(markers[j].id);
                                markers[j].nearMarkers.push(markers[i].id);

                                markers[i].nearMarkers.push(markers[j].id);
                                markers[j].nearMarkers.push(markers[i].id);

                                markers[i].nearMarkersInfo.push({distance: max_distance - distance, })

                            }
                        }
                    }

                    markers.forEach(marker => {
                        marker.callout.content += ` (${marker.nearbyCount})`;
                    });

                    that.setData({
                        markers: markers,
                        orders: orders,
                        selected_ids: [],
                        main_order_ids
                    })
                    Notify({
                        type: 'success',
                        message: '数据加载完成'
                    });


                }
            }
        })
    },
    //根据距离计算远近
    sort_orders(orders) {
        let arr = newArray;
        let s = "";
        for (var i = 1; i < arr.length; i++) {
          for (var j = i; j > 0; j--) {
            if (arr[j].distance > arr[j - 1].distance) {
              s = arr[j];
              arr[j] = arr[j - 1];
              arr[j - 1] = s;
            }
          }
        }
       return newArray.reverse();
       
      },
    // 经纬度计算距离

    getDistance( lat1,  lng1,  lat2,  lng2){
        var radLat1 = lat1*Math.PI / 180.0;
        var radLat2 = lat2*Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s *6378.137 ;// EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        s = s.toFixed(2);
        return parseFloat(s);
    },
    calculateDistance(lat1, lon1, lat2, lon2) {
        function toRad(x) {
            return x * Math.PI / 180;
        }

        let R = 6371; // 地球半径（公里）
        let dLat = toRad(lat2 - lat1);
        let dLon = toRad(lon2 - lon1);
        let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
        let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        let distance = R * c;
        return distance * 1000; // 转换为米
    },


    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
       //this.get_waiting_delivery()
       //wx.stopPullDownRefresh()

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
       
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //点击导航事件
    getLocation(e) {
        const that = this
        let index = e.currentTarget.dataset['index']; //获取传递的参数
        let order = that.data.orders[index]

        var address = order.address
        var contact = order.contact
        var mobile = order.mobile
        var latitude = order.latitude
        var longitude =order.longitude
        wx.openLocation({
            latitude: Number(latitude), //要去的纬度-地址 一定不要使数字
            longitude: Number(longitude), //要去的经度-地址
            address: address,
            name: contact + '/' + mobile,
            scale: 15
        })
    },
    //点击展开
    onAddress(event) {
        this.setData({
            activeNames: event.detail,
        });
    },

    onUnbind(e) {
        let that = this
        let current_delivery_man_id = that.data.delivery_man.delivery_man_id
        let current_delivery_district_id = that.data.current_delivery_district_id
        let contact = e.currentTarget.dataset.contact
        let order_id = e.currentTarget.dataset.order_id
        let order_no = e.currentTarget.dataset.order_no

        Dialog.confirm({
            title: '解绑',
            message: '确定要解绑\n[' + contact + '] \n订单号: [' + order_no + '] \n的订单？',
        })
            .then(() => {

                wx.request({
                    url: app.globalData.API + '/delivery/index/unbind-order',
                    header: {
                        'Content-Type': 'application/json',
                        "x-api-key": this.data.access_token,
                    },
                    method: "POST",
                    data: {
                        current_delivery_district_id,
                        current_delivery_man_id,
                        order_id,
                    },
                    success(res) {
                        if (res.data.code === 200) {
                            Toast('解绑成功~')
                            that.onClose()
                            that.get_in_return()
                        } else {
                            Toast('解绑失败~')
                        }
                    }
                })
            })
            .catch(() => {
                // on cancel
                Toast('解绑失败~')
            });


    },
    onClose() {
        this.setData({
            fileList: [],
            values: '',
            ball: false,
            dshow: true,
        })
    },

    orderBydata(event){
        var order_id = event.target.dataset.id;
        var name = event.target.dataset.name;
        wx.navigateTo({
            url: '/templates/deliver/pages/order/order?order_id='+ order_id+'&name='+name,
        })
    }
})